import checkFileType from '@/utils/checkFileType.js';
import { Toast } from 'vant';
export default function compressImage(file) {
  // 检验文件类型
  var bool = checkFileType(file.name, ['png', 'jpg', 'JPEG', 'jpeg', 'PNG', 'JPG']);
  if (!bool) {
    Toast('文件类型不支持，请重新上传');
    return;
  }
  const fileSize = file.size;
  const read = new FileReader();
  read.readAsDataURL(file);
  var base64;
  read.onload = function(e) {
    const img = new Image();
    img.src = e.target.result;
    img.onload = function() {
      // 默认按比例压缩
      if (fileSize > 20971520) {
        Toast('图片过大，请重新选择');
        return;
      }
      const w = img.width;
      const h = img.height;
      const canvas = document.createElement('canvas');
      const ctx = canvas.getContext('2d');
      canvas.setAttribute('width', w);
      canvas.setAttribute('height', h);
      ctx.drawImage(this, 0, 0, w, h);
      base64 = canvas.toDataURL('image/jpeg', 1);
      return base64;
    };
  };
}
